<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

class BookingSystem {
    private $dataFile = 'data/bookings.json';
    private $roomsFile = 'data/rooms.json';

    public function __construct() {
        // 确保数据目录存在
        if (!file_exists('data')) {
            mkdir('data', 0777, true);
        }
    }

    public function handleRequest() {
        try {
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!$input) {
                throw new Exception('无效的请求数据');
            }

            switch ($input['action'] ?? '') {
                case 'getRooms':
                    return $this->getRoomsStatus();
                case 'getTimeSlots':
                    return $this->getTimeSlots($input['roomId'], $input['date']);
                case 'book':
                    return $this->handleBooking($input);
                case 'cancel':
                    return $this->handleCancellation($input);
                default:
                    throw new Exception('未知的操作类型');
            }
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    private function getRoomsStatus() {
        $rooms = $this->loadRooms();
        $bookings = $this->loadBookings();
        $today = date('Y-m-d');

        foreach ($rooms as &$room) {
            $room['availableSlots'] = $this->countAvailableSlots($room['id'], $today, $bookings);
            $room['nextAvailable'] = $this->findNextAvailableSlot($room['id'], $today, $bookings);
        }

        return $this->success(['rooms' => $rooms]);
    }

    private function getTimeSlots($roomId, $date) {
        $bookings = $this->loadBookings();
        $timeSlots = $this->generateTimeSlots();
        // 获取指定房间和日期的所有预约记录
        $roomBookings = isset($bookings[$roomId][$date]) ? 
            array_column($bookings[$roomId][$date], 'time') : 
            [];

        foreach ($timeSlots as &$slot) {
            $slot['available'] = !in_array($slot['time'], $roomBookings);
        }

        return $this->success(['timeSlots' => $timeSlots]);
    }

    private function handleBooking($data) {
        $this->validateBookingData($data);

        $bookings = $this->loadBookings();
        $bookingKey = $this->generateBookingKey($data);

        // 检查时段是否已被预约
        if ($this->isTimeSlotBooked($bookings, $data)) {
            throw new Exception('该时段已被预约');
        }

        // 添加预约记录
        $bookings[$data['roomId']][$data['date']][] = [
            'time' => $data['time'],
            'bookingTime' => date('Y-m-d H:i:s'),
            'status' => 'confirmed'
        ];

        $this->saveBookings($bookings);
        
        // 发送预约确认
        $this->sendBookingConfirmation($data);

        return $this->success([
            'message' => '预约成功',
            'bookingId' => $bookingKey
        ]);
    }

    private function handleCancellation($data) {
        $bookings = $this->loadBookings();
        
        if (!$this->isTimeSlotBooked($bookings, $data)) {
            throw new Exception('未找到该预约记录');
        }

        // 移除预约记录
        $timeSlots = &$bookings[$data['roomId']][$data['date']];
        $timeSlots = array_filter($timeSlots, function($slot) use ($data) {
            return $slot['time'] !== $data['time'];
        });

        $this->saveBookings($bookings);

        return $this->success(['message' => '取消预约成功']);
    }

    private function generateTimeSlots() {
        return [
            ['time' => '09:00', 'period' => 'morning'],
            ['time' => '10:00', 'period' => 'morning'],
            ['time' => '11:00', 'period' => 'morning'],
            ['time' => '14:00', 'period' => 'afternoon'],
            ['time' => '15:00', 'period' => 'afternoon'],
            ['time' => '16:00', 'period' => 'afternoon'],
            ['time' => '17:00', 'period' => 'afternoon']
        ];
    }

    private function countAvailableSlots($roomId, $date, $bookings) {
        $totalSlots = count($this->generateTimeSlots());
        $bookedSlots = count($bookings[$roomId][$date] ?? []);
        return $totalSlots - $bookedSlots;
    }

    private function findNextAvailableSlot($roomId, $date, $bookings) {
        $timeSlots = $this->generateTimeSlots();
        $bookedTimes = array_column($bookings[$roomId][$date] ?? [], 'time');

        foreach ($timeSlots as $slot) {
            if (!in_array($slot['time'], $bookedTimes)) {
                return $slot['time'];
            }
        }

        return null;
    }

    private function validateBookingData($data) {
        $required = ['roomId', 'date', 'time'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                throw new Exception("缺少必要字段: {$field}");
            }
        }

        // 验证日期格式
        if (!strtotime($data['date'])) {
            throw new Exception('无效的日期格式');
        }

        // 验证时间格式
        if (!preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $data['time'])) {
            throw new Exception('无效的时间格式');
        }
    }

    private function sendBookingConfirmation($data) {
        // 这里可以实现发送邮件或其他通知的逻辑
        // 示例仅记录日志
        $logMessage = sprintf(
            "[%s] 新预约: 房间%s, 日期%s, 时间%s\n",
            date('Y-m-d H:i:s'),
            $data['roomId'],
            $data['date'],
            $data['time']
        );
        file_put_contents('data/booking.log', $logMessage, FILE_APPEND);
    }

    private function loadBookings() {
        return $this->loadJsonFile($this->dataFile, []);
    }

    private function loadRooms() {
        return $this->loadJsonFile($this->roomsFile, [
            ['id' => 1, 'name' => '咨询室 A'],
            ['id' => 2, 'name' => '咨询室 B'],
            ['id' => 3, 'name' => '咨询室 C']
        ]);
    }

    private function loadJsonFile($file, $default) {
        if (file_exists($file)) {
            $data = json_decode(file_get_contents($file), true);
            return $data !== null ? $data : $default;
        }
        return $default;
    }

    private function saveBookings($bookings) {
        file_put_contents($this->dataFile, json_encode($bookings, JSON_PRETTY_PRINT));
    }

    private function generateBookingKey($data) {
        return md5($data['roomId'] . $data['date'] . $data['time'] . time());
    }

    private function isTimeSlotBooked($bookings, $data) {
        return isset($bookings[$data['roomId']][$data['date']]) &&
               in_array($data['time'], array_column($bookings[$data['roomId']][$data['date']], 'time'));
    }

    private function success($data) {
        return array_merge(['success' => true], $data);
    }

    private function error($message) {
        return [
            'success' => false,
            'message' => $message
        ];
    }
}

// 处理请求
$system = new BookingSystem();
echo json_encode($system->handleRequest());
?> 